import os, sys, logging
import datetime
from optparse import OptionParser


APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEAUTH_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("Must Set SIMPLEAUTH_INSTALL in the environment!")

sys.path.append(os.path.join(APPLICATION_INSTALL_DIR, "lib%spython" % os.sep))

from simple_auth.resource_builder import *

log = None

# initialize logger
today = datetime.date.today().strftime("%Y-%m-%d")

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s',
                    filename='SimpleAuthResourceBuilder.%s.log' % today,
                    filemode='a')

console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)s %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
log = logging.getLogger('')


def build_db_resource(resource_name, configPath=None):
    db_rb = DBResourceBuilder(resource_name, configPath=configPath)
    try:
        db_rb.build()
    except ResourceBuilderException, e:
        logging.info("Unable to build resource!  Error: %s" % str(e))
        return False
    return True


def main():
    usage = "usage: %prog {-t, --type} resource type (db|domain|ldap) {-n, --name} resource name {-p, --path} resource config path"
    parser = OptionParser(usage)
    parser.add_option("-t", "--type", dest="type", help="type of resource to build")
    parser.add_option("-n", "--name", dest="name", help="name of resource")
    parser.add_option("-p", "--path", dest="path", help="path to find config")
    (options, args) = parser.parse_args()


    type = options.type
    name = options.name
    path = options.path
    if (not type) or (not name):
        parser.error("Must have at least type and name of resource config")
        
    if type.lower() == "db":
        if build_db_resource(name, path):
            logging.info("Database resource %s built!" % name)
        else:
            logging.info("Database resource %s FAILED to build!" % name)
            
if __name__ == "__main__":
    main()
